package com.logistics.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.logistics.entity.LoginUser;
import com.logistics.pojo.Employee;
import com.logistics.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;

@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private EmployeeService employeeService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //用户的角色权限
        List<GrantedAuthority> roleList = new ArrayList<>();
        //授权(这里的授权只是用来骗过SpringSecurity框架的检验的，没有实际意义)
        roleList.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        //把用户账号密码权限都传给SpringSecurity的User对象，它会进行校验密码正常

        //创建查询对象
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username",username);
        Employee employee = employeeService.getOne(queryWrapper);

        //健壮性
        if(ObjectUtils.isEmpty(employee)){
//            throw new RuntimeException("用户不存在！");
            //编写自定义异常 log文件系统维护
            System.out.println("用户不存在");
            return null;
        }

        //通过employee 的角色 赋一定的权限

        //必须使用BCrypt加密后的
        // $2a$10$rFFlbQlTUkY4VK/hUrLDguDqYmp.1U.LPf8k0HisgAaZ1ueDsAM46
//        return new User(username,employee.getPassword(),roleList);
        //密码必须是明文 非加密的
//        return new User(username,new BCryptPasswordEncoder().encode(employee.getPassword()),roleList);
        employee.setPassword(new BCryptPasswordEncoder().encode(employee.getPassword()).toString());
        return new LoginUser(employee);
    }
}
